package com.example.mychat.view

import android.animation.Animator
import android.animation.AnimatorListenerAdapter
import android.animation.AnimatorSet
import android.animation.ObjectAnimator
import android.animation.ValueAnimator
import android.content.Context
import android.graphics.Color
import android.graphics.drawable.GradientDrawable
import android.util.AttributeSet
import android.view.LayoutInflater
import android.view.View
import android.view.animation.AccelerateDecelerateInterpolator
import android.view.animation.LinearInterpolator
import android.view.animation.OvershootInterpolator
import android.widget.FrameLayout
import android.widget.ImageView
import android.widget.TextView
import com.example.mychat.R

class LoadingButton @JvmOverloads constructor(
    context: Context,
    attrs: AttributeSet? = null,
    defStyleAttr: Int = 0
) : FrameLayout(context, attrs, defStyleAttr) {

    private val normalText: TextView
    private val loadingView: View
    private val successView: ImageView
    private val buttonBackground: View
    private val dot1: View
    private val dot2: View
    private val dot3: View
    private var animatorSet: AnimatorSet? = null
    private val animationDuration = 300L
    private var originalWidth = 0
    private var originalHeight = 0
    private val buttonContent: View

    init {
        val view = LayoutInflater.from(context).inflate(R.layout.loading_button, this, true)
        normalText = view.findViewById(R.id.normalText)
        loadingView = view.findViewById(R.id.loadingView)
        successView = view.findViewById(R.id.successView)
        buttonBackground = view.findViewById(R.id.buttonBackground)
        buttonContent = view.findViewById(R.id.buttonContent)
        dot1 = loadingView.findViewById(R.id.dot1)
        dot2 = loadingView.findViewById(R.id.dot2)
        dot3 = loadingView.findViewById(R.id.dot3)

        post {
            originalWidth = width
            originalHeight = height
            updateBackground(originalWidth, Color.parseColor("#05BE5E"))
        }
    }

    private fun updateBackground(width: Int, color: Int) {
        val cornerRadius = if (width <= originalHeight) {
            originalHeight / 2f
        } else {
            resources.getDimension(R.dimen.button_corner_radius)
        }

        buttonBackground.background = GradientDrawable().apply {
            shape = GradientDrawable.RECTANGLE
            setColor(color)
            this.cornerRadius = cornerRadius
        }
    }

    fun startLoading() {
        normalText.visibility = View.INVISIBLE
        loadingView.visibility = View.VISIBLE
        successView.visibility = View.INVISIBLE
        startDotAnimation()
    }

    fun showSuccess() {
        stopAnimation()
        
        // 创建收缩动画
        val targetWidth = originalHeight
        val marginAnim = ValueAnimator.ofInt(0, (originalWidth - targetWidth) / 2).apply {
            duration = 500
            interpolator = AccelerateDecelerateInterpolator()
            addUpdateListener { animator ->
                val margin = animator.animatedValue as Int
                val params = layoutParams as MarginLayoutParams
                params.marginStart = margin
                params.marginEnd = margin
                layoutParams = params

                val currentWidth = originalWidth - 2 * margin
                val params2 = buttonBackground.layoutParams
                params2.width = currentWidth
                buttonBackground.layoutParams = params2

                // 计算当前进度
                val progress = margin.toFloat() / ((originalWidth - targetWidth) / 2)
                
                // 更新内容容器的透明度
                buttonContent.alpha = 1 - progress

                // 更新背景颜色和形状
                val color = evaluateColor(progress, 
                    Color.parseColor("#05BE5E"),
                    Color.parseColor("#05BE5E")
                )
                updateBackground(currentWidth, color)
            }
            addListener(object : AnimatorListenerAdapter() {
                override fun onAnimationEnd(animation: Animator) {
                    // 隐藏原始内容
                    buttonContent.visibility = View.GONE
                    
                    // 显示成功图标
                    successView.visibility = View.VISIBLE
                    successView.alpha = 0f
                    successView.scaleX = 0f
                    successView.scaleY = 0f

                    val successAnim = AnimatorSet().apply {
                        playTogether(
                            ObjectAnimator.ofFloat(successView, "alpha", 0f, 1f),
                            ObjectAnimator.ofFloat(successView, "scaleX", 0f, 1f),
                            ObjectAnimator.ofFloat(successView, "scaleY", 0f, 1f)
                        )
                        duration = 300
                        interpolator = OvershootInterpolator()
                    }
                    successAnim.start()
                }
            })
        }
        marginAnim.start()
    }

    private fun evaluateColor(fraction: Float, startColor: Int, endColor: Int): Int {
        val startA = Color.alpha(startColor)
        val startR = Color.red(startColor)
        val startG = Color.green(startColor)
        val startB = Color.blue(startColor)

        val endA = Color.alpha(endColor)
        val endR = Color.red(endColor)
        val endG = Color.green(endColor)
        val endB = Color.blue(endColor)

        return Color.argb(
            (startA + (endA - startA) * fraction).toInt(),
            (startR + (endR - startR) * fraction).toInt(),
            (startG + (endG - startG) * fraction).toInt(),
            (startB + (endB - startB) * fraction).toInt()
        )
    }

    fun reset() {
        stopAnimation()
        val params = layoutParams as MarginLayoutParams
        params.marginStart = 0
        params.marginEnd = 0
        layoutParams = params

        val bgParams = buttonBackground.layoutParams
        bgParams.width = originalWidth
        buttonBackground.layoutParams = bgParams

        updateBackground(originalWidth, Color.parseColor("#2196F3"))
        normalText.visibility = View.VISIBLE
        loadingView.visibility = View.INVISIBLE
        successView.visibility = View.INVISIBLE
    }

    private fun startDotAnimation() {
        stopAnimation()
        
        val delay = 120L

        val dot1Anim = createDotAnimator(dot1, 0)
        val dot2Anim = createDotAnimator(dot2, delay)
        val dot3Anim = createDotAnimator(dot3, delay * 2)

        animatorSet = AnimatorSet().apply {
            playTogether(dot1Anim, dot2Anim, dot3Anim)
            duration = animationDuration
            interpolator = LinearInterpolator()
            start()
        }
    }

    private fun createDotAnimator(dot: View, startDelay: Long): ObjectAnimator {
        return ObjectAnimator.ofFloat(dot, "translationY", 0f, -15f, 0f).apply {
            this.startDelay = startDelay
            repeatCount = ValueAnimator.INFINITE
            repeatMode = ValueAnimator.RESTART
        }
    }

    private fun stopAnimation() {
        animatorSet?.cancel()
        animatorSet = null
        dot1.translationY = 0f
        dot2.translationY = 0f
        dot3.translationY = 0f
    }
} 